package tk.mybatis.springboot.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.umuw.core.util.ApplicationUtils;
import com.umuw.core.util.MD5;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import tk.mybatis.mapper.util.StringUtil;
import tk.mybatis.springboot.api.controller.BaseController;
import tk.mybatis.springboot.mapper.CoverageMapper;
import tk.mybatis.springboot.mapper.CoveragedateMapper;
import tk.mybatis.springboot.mapper.TAccountMapper;
import tk.mybatis.springboot.mapper.TCarInsuranceMapper;
import tk.mybatis.springboot.mapper.TCarInsuranceOrderMapper;
import tk.mybatis.springboot.mapper.TCarTypesMapper;
import tk.mybatis.springboot.mapper.TCarprofileMapper;
import tk.mybatis.springboot.mapper.TCityMapper;
import tk.mybatis.springboot.mapper.TCustomerInfoMapper;
import tk.mybatis.springboot.mapper.TInsOrderCostMapper;
import tk.mybatis.springboot.mapper.TInsuranceTypeListMapper;
import tk.mybatis.springboot.mapper.TInsuranceTypesMapper;
import tk.mybatis.springboot.mapper.TInsuranceUnitMapper;
import tk.mybatis.springboot.mapper.TProvinceMapper;
import tk.mybatis.springboot.mapper.TReceiversMapper;
import tk.mybatis.springboot.mapper.TUserprofileMapper;
import tk.mybatis.springboot.mapper.TUserprofilePn2mMapper;
import tk.mybatis.springboot.mapper.TWeixinAddressMapper;
import tk.mybatis.springboot.mapper.WeixinInsuranceMapper;
import tk.mybatis.springboot.mapper.WeixinOwnerMapper;
import tk.mybatis.springboot.mapper.WeixinTruckInfoMapper;
import tk.mybatis.springboot.mapper.WeixinUserMapper;
import tk.mybatis.springboot.model.Accurate;
import tk.mybatis.springboot.model.CalculateApiReqMsg;
import tk.mybatis.springboot.model.CalculateApiResultMsg;
import tk.mybatis.springboot.model.CarInfo;
import tk.mybatis.springboot.model.CarInfoReqMsg;
import tk.mybatis.springboot.model.CarInsurancePrice;
import tk.mybatis.springboot.model.Coverage;
import tk.mybatis.springboot.model.Coveragedate;
import tk.mybatis.springboot.model.CustomerResult;
import tk.mybatis.springboot.model.InformationMsg;
import tk.mybatis.springboot.model.Insurance;
import tk.mybatis.springboot.model.Message;
import tk.mybatis.springboot.model.OrderResultMsg;
import tk.mybatis.springboot.model.PersonInfo;
import tk.mybatis.springboot.model.Province;
import tk.mybatis.springboot.model.QueryInsurReqMsg;
import tk.mybatis.springboot.model.Reinsurance;
import tk.mybatis.springboot.model.ReinsuranceReqMsg;
import tk.mybatis.springboot.model.SimulateApiReqMsg;
import tk.mybatis.springboot.model.TAccount;
import tk.mybatis.springboot.model.TCarInsurance;
import tk.mybatis.springboot.model.TCarInsuranceOrder;
import tk.mybatis.springboot.model.TCarInsuranceOrderExtend;
import tk.mybatis.springboot.model.TCarTypes;
import tk.mybatis.springboot.model.TCarprofile;
import tk.mybatis.springboot.model.TCity;
import tk.mybatis.springboot.model.TCustomerInfo;
import tk.mybatis.springboot.model.TInsOrderCost;
import tk.mybatis.springboot.model.TInsOrderCostExtends;
import tk.mybatis.springboot.model.TInsuranceTypeList;
import tk.mybatis.springboot.model.TInsuranceTypes;
import tk.mybatis.springboot.model.TProvince;
import tk.mybatis.springboot.model.TReceivers;
import tk.mybatis.springboot.model.TUserprofile;
import tk.mybatis.springboot.model.TUserprofilePn2m;
import tk.mybatis.springboot.model.TWeixinAddress;
import tk.mybatis.springboot.model.TWeixinInsurance;
import tk.mybatis.springboot.model.TWeixinOwner;
import tk.mybatis.springboot.model.TWeixinTruckInfo;
import tk.mybatis.springboot.model.TWeixinUser;
import tk.mybatis.springboot.service.WexinInsuranceService;
import tk.mybatis.springboot.share.util.PhoneCode;
import tk.mybatis.springboot.share.util.PropertiesUtil;
import tk.mybatis.springboot.wexin.bean.Userinfo;
import tk.mybatis.springboot.wexin.util.ECXBUtils;
import tk.mybatis.springboot.wexin.util.RedisUtils;
import tk.mybatis.springboot.wexin.util.UniqId;

@Service
@Transactional
public class WexinInsuranceServiceImpl implements WexinInsuranceService{
	@Autowired
	private WeixinUserMapper weixinUserMapper;
	
	@Autowired
	private WeixinTruckInfoMapper weixinTruckInfoMapper;
	
	@Autowired
	private WeixinOwnerMapper weixinOwnerMapper;
	
	@Autowired
	private WeixinInsuranceMapper weixinInsuranceMapper;
	
	@Autowired
	private TCityMapper tCityMapper;
	
	@Autowired
	private TProvinceMapper tProvinceMapper;
	
	@Autowired
	private CoverageMapper coverageMapper;
	
	@Autowired
	private CoveragedateMapper coveragedateMapper;
	
	@Autowired
	private TInsuranceTypeListMapper tInsuranceTypeListMapper;
	
	@Autowired
	private TWeixinAddressMapper tWeixinAddressMapper;
	
	@Autowired
	private TCarInsuranceMapper tCarInsuranceMapper;
	
	@Autowired
	private TReceiversMapper tReceiversMapper;
	
	@Autowired
	private TCustomerInfoMapper tCustomerInfoMapper;
	
	@Autowired
	private TCarprofileMapper tCarprofileMapper;
	
	@Autowired
	private TCarTypesMapper tCarTypesMapper;
	
	@Autowired
	private TInsuranceUnitMapper tInsuranceUnitMapper;
	
	@Autowired
	private TCarInsuranceOrderMapper tCarInsuranceOrderMapper;
	
	@Autowired
	private TUserprofileMapper tUserprofileMapper;
	
	@Autowired
	private TUserprofilePn2mMapper tUserprofilePn2mMapper;
	
	@Autowired
	private TInsuranceTypesMapper tInsuranceTypesMapper;
	
	@Autowired
	private TAccountMapper tAccountMapper;
	
	@Autowired
	private TInsOrderCostMapper tInsOrderCostMapper;
	private static Logger log = LogManager.getLogger(ECXBUtils.class);
	@Override
	public List<TWeixinUser> getWeixinUsers(String openid) {
		return weixinUserMapper.getWeixinUsers(openid);
	}
	@Override
	public Message saveTruckCard(HttpServletRequest request, String openid, String truckCard, String cityCode, String provinceID) throws Exception {
		TWeixinUser weixinUser = new TWeixinUser();
		weixinUser.setOpenid(openid);
		weixinUser.setTruckcard(truckCard);
		List<TWeixinUser> tWeixinUsers = weixinUserMapper.select(weixinUser);
		if(tWeixinUsers.size() == 0){
			weixinUser.setId(UniqId.getUid());
			weixinUser.setCreatedate(new Date());
			weixinUserMapper.insertSelective(weixinUser);		
		}else{
			weixinUser = tWeixinUsers.get(0);
		}
		List<Insurance> insurers = tProvinceMapper.findInsurance(provinceID);
		String insurerCode = "";
		for (Insurance insurance : insurers) {
			insurerCode += insurance.getInsurerCode() + ",";
		}
		insurerCode = insurerCode.substring(0, insurerCode.length() -1);
		CarInsurancePrice carInsurancePrice= new CarInsurancePrice(); 
		carInsurancePrice.setLicenseNo(truckCard);
		CarInfo carInfo = new CarInfo(); 
		carInfo.setLicenseNo(truckCard);
		TWeixinTruckInfo findTruckInfo = weixinTruckInfoMapper.findTruckInfo(weixinUser.getId());
		if(findTruckInfo == null){
			CarInfoReqMsg carInfoReqMsg = CarInfoReqMsg.buildMessage(carInfo);
			JSONObject callApi = ECXBUtils.callApi(carInfoReqMsg, PropertiesUtil.getMessage("carInfo"));
			if(!"1".equals(callApi.get("state"))){
				return BaseController.error("0201");
			}
			JSONObject date = callApi.getJSONObject("data"); 
			List<String> vehicleList = Lists.newArrayList();
			JSONArray jsonArray = date.getJSONArray("vehicleList");
			JSONObject one = JSONObject.fromObject(jsonArray.get(0));
			carInfo.setFrameNo(one.getString("vin"));
			carInfo.setEngineNo(one.getString("engineNo"));
			carInfo.setBrandCode(one.getString("brandCode"));
			carInfo.setBrandName(one.getString("brandName"));
			carInfo.setIsTrans(one.getString("isTrans"));
			carInfo.setTransDate(one.getString("transDate"));
			carInfo.setRegisterDate(one.getString("registerDate"));
			carInfo.setVehicleFgwCode(one.getString("vehicleFgwCode"));
			for (Object object : jsonArray) {
				JSONObject fromObject = JSONObject.fromObject(object);
				StringBuffer sb = new StringBuffer();
				sb.append(fromObject.get("standardName"));
				sb.append(fromObject.get("engineDesc"));
				sb.append(fromObject.get("parentVehName"));
				vehicleList.add(sb.toString());
			}
			carInsurancePrice.setCarMode(vehicleList);
		}else{
			carInfo.setFrameNo(findTruckInfo.getFrameno());
			carInfo.setEngineNo(findTruckInfo.getEngineno());
			carInfo.setBrandName(findTruckInfo.getBrandname());
			carInfo.setBrandCode(findTruckInfo.getBrandcode());
			carInfo.setIsTrans(findTruckInfo.getIstrans());
			carInfo.setRegisterDate(findTruckInfo.getRegisterdate());
			carInfo.setTransDate(findTruckInfo.getTransdate());
			carInfo.setVehicleFgwCode(findTruckInfo.getVehiclefgwcode());
			List<String> vehicleList = Lists.newArrayList();
			vehicleList.add(findTruckInfo.getBrandname());
			carInsurancePrice.setCarMode(vehicleList);
		}
		SimulateApiReqMsg simulateApiReqMsg = null;
		List<Coverage> selectAll = coverageMapper.selectAllByUser(weixinUser.getId());
		if(selectAll.size() == 0){	
			QueryInsurReqMsg queryInsurReqMsg = QueryInsurReqMsg.buildMessage(carInfo);
			JSONObject queryInsur = ECXBUtils.callApi(queryInsurReqMsg, PropertiesUtil.getMessage("queryInsur"));
			if(!"1".equals(queryInsur.get("state"))){
				return Message.error(queryInsur.getString("msg"));
			}		
			if(queryInsur.getJSONObject("data") == null){
				simulateApiReqMsg =  getSimulateApiReqMsg(carInfo, cityCode, insurerCode);
			}else{
				JSONObject fromObject = JSONObject.fromObject(queryInsur.getJSONObject("data"));
				List<Coverage> coverageList = null;
				if(!"null".equals(fromObject.getString("coverageList"))){ 
					coverageList = fromObject.getJSONArray("coverageList");
					for (Insurance insurance : insurers) {
						if(insurance.getInsurerCode().equals(fromObject.getString("insurerCode"))){
							insurance.setIsRenewal(true);
						}
					}
					simulateApiReqMsg =  SimulateApiReqMsg.buildMessage(carInfo, insurerCode, 
							fromObject.getString("biBeginDate"), fromObject.getString("ciBeginDate"), cityCode, coverageList);
				}else{
					simulateApiReqMsg =  getSimulateApiReqMsg(carInfo, cityCode, insurerCode);
				}
			}
		}else{
			Coveragedate findCoveragedate = coveragedateMapper.findCoveragedate(weixinUser.getId());
			simulateApiReqMsg =  SimulateApiReqMsg.buildMessage(carInfo, insurerCode, 
					findCoveragedate.getBibegindate(), findCoveragedate.getCibegindate(), cityCode, selectAll);
		}
		HttpSession session = request.getSession();
		JSONObject simulateApi = ECXBUtils.callApi(simulateApiReqMsg, PropertiesUtil.getMessage("SimulateApi"));
		if("1".equals(simulateApi.get("state"))){
			JSONObject simulateDate = simulateApi.getJSONObject("data");
			if("1".equals(simulateDate.get("state"))){
				JSONArray jsonArrays= simulateDate.getJSONArray("Data");
				for (int x=0;x<insurers.size();x++) {
					Insurance insurance = insurers.get(x);
					for (Object object : jsonArrays) {
						JSONObject fromObject = JSONObject.fromObject(object);
						if(insurance.getInsurerCode().equals(fromObject.getString("insurerCode"))){
							insurance.setQuoteResult(object);
						}
					}
					if(insurance.getQuoteResult() == null){
						insurers.remove(insurance);
						x--;
					}
				}
				carInsurancePrice.setInsurance(Message.success("Success", insurers));
			}else{
				return BaseController.error("9999");
			}
		}else{
			return Message.error(simulateApi.getString("msg"));
		}
		session.setAttribute("userid", weixinUser.getId());
		session.setAttribute("simulateApiReqMsg", simulateApiReqMsg);
		session.setAttribute("carInsurancePrice", carInsurancePrice);
		return BaseController.success("成功", carInsurancePrice);
	
		
	
	}
	private SimulateApiReqMsg getSimulateApiReqMsg(CarInfo carInfo, String cityCode, String insurerCode) {
		Date date=new  Date();//取时间 
		Calendar calendar = new GregorianCalendar(); 
		calendar.setTime(date); 
		calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动 
		date=calendar.getTime();   //这个时间就是日期往后推一天的结果 
		String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
		List<Coverage> coverageList = coverageMapper.selectTemp();
		SimulateApiReqMsg simulateApiReqMsg =  SimulateApiReqMsg.buildMessage(carInfo, insurerCode, 
				time, time, cityCode, coverageList);
		return simulateApiReqMsg;
	}
	@Override
	public TWeixinTruckInfo saveTruckInfo(String userId, String vin, String engine, Date creationdate,
			Integer istransfer, Date istransferdate) {
		
		return null;
	}
	@Override
	public TWeixinTruckInfo getTruckInfo(String userId) {
		return weixinTruckInfoMapper.findTruckInfo(userId);
	}
	@Override
	public TWeixinOwner getOwner(String userId) {
		// TODO Auto-generated method stub
		return weixinOwnerMapper.findWeixinOwner(userId);
	}
	@Override
	public TWeixinOwner saveOwner(String userId, String ownerName, String idCard, String phone) {
		TWeixinOwner weixinOwner = new TWeixinOwner();
		weixinOwner.setIdcard(idCard);
		weixinOwner.setOwnername(ownerName);
		weixinOwner.setUserid(userId);
		weixinOwner.setPhone(phone);
		weixinOwner.setModifydate(new Date());
		TWeixinOwner findWeixinOwner = weixinOwnerMapper.findWeixinOwner(userId);
		if(findWeixinOwner == null){
			weixinOwner.setId(UniqId.getUid());
			weixinOwner.setCreatedate(new Date());
			weixinOwnerMapper.insertSelective(weixinOwner);
		}else{
			weixinOwner.setId(findWeixinOwner.getId());
			weixinOwnerMapper.updateByPrimaryKeySelective(weixinOwner);
		}
		return weixinOwner;
	}
	@Override
	public TWeixinInsurance getInsurance(String userId) {
		return weixinInsuranceMapper.findWeixinInsurance(userId);
	}
	@Override
	public TWeixinInsurance saveInsurance(TWeixinInsurance info) {
		TWeixinInsurance findWeixinInsurance = weixinInsuranceMapper.findWeixinInsurance(info.getUserid());
		info.setModifydate(new Date());
		if(findWeixinInsurance == null){
			info.setCreatedate(new Date());
			info.setId(UniqId.getUid());
			weixinInsuranceMapper.insertSelective(info);
		}else{
			info.setId(findWeixinInsurance.getId());
			weixinInsuranceMapper.updateByPrimaryKeySelective(info);
		}
		return info;
	}
	@Override
	public Message getInsurancetypes() throws Exception {
		List<TInsuranceTypeList> findAll = tInsuranceTypeListMapper.findAll();
		return Message.success("Success", findAll);
	}
	@Override
	public Message getProvince() throws Exception {
		List<TProvince> findAll = tProvinceMapper.findAll();
		return Message.success("Success", findAll);
	}
	@Override
	public Message getCity(String provinceId) throws Exception {
		List<TCity> findAll = tCityMapper.findAll(provinceId);
		return Message.success("Success", findAll);
	}
	@Override
	public Message carQuery(String brandName, String page) throws Exception {
		InformationMsg buildMessage = InformationMsg.buildMessage(brandName, page);
		JSONObject information = ECXBUtils.callApi(buildMessage, PropertiesUtil.getMessage("informationUrl"));
		if("1".equals(information.getString("state")) && !"null".equals(information.getString("data"))){
			JSONArray jsonArray = information.getJSONArray("data");
			Map<String,String> map = new HashMap<String,String>();
			for (Object object : jsonArray) {
				JSONObject fromObject = JSONObject.fromObject(object);
				map.put(fromObject.getString("brandCode"), fromObject.getString("brandName") + " " +
						fromObject.getString("engineDesc") + fromObject.getString("remark"));
				List<TCarTypes> tCarType = tCarTypesMapper.findByBrandCode(fromObject.getString("brandCode"));
				if(tCarType.size() == 0){
					TCarTypes tCarTypes =  new TCarTypes();
					tCarTypes.setType_name(fromObject.getString("brandName"));
					tCarTypes.setVehicleFgwCode(fromObject.getString("vehicleFgwCode"));
					tCarTypes.setBrandCode(fromObject.getString("brandCode"));
					tCarTypes.setBrandName(fromObject.getString("brandName"));
					tCarTypes.setEngineDesc(fromObject.getString("engineDesc"));
					tCarTypes.setFamilyName(fromObject.getString("familyName"));
					tCarTypes.setRemark(fromObject.getString("remark"));
					tCarTypes.setNewCarPrice(fromObject.getString("newCarPrice"));
					tCarTypes.setPurchasePrice(fromObject.getString("newCarPrice"));
					tCarTypes.setImportFlag(fromObject.getString("importFlag"));
					tCarTypes.setPurchasePriceTax(fromObject.getString("purchasePriceTax"));
					tCarTypes.setSeat(fromObject.getString("seat"));
					tCarTypes.setStandardName(fromObject.getString("standardName"));
					tCarTypes.setMsg("msg");
					tCarTypesMapper.myInsert(tCarTypes);
				}
			}
			return Message.success("成功", map);
		}else{
			return Message.error("");
		}
	}
	@Override
	public Message vehicle(HttpServletRequest request, CarInfo carInfo) throws Exception {
		HttpSession session = request.getSession();
		String userid = session.getAttribute("userid").toString();
		CarInsurancePrice carInsurancePrice= (CarInsurancePrice)session.getAttribute("carInsurancePrice");
		List<String> vehicleList = Lists.newArrayList();
		vehicleList.add(carInfo.getBrandName());
		carInsurancePrice.setCarMode(vehicleList);
		SimulateApiReqMsg simulateApiReqMsg = (SimulateApiReqMsg)session.getAttribute("simulateApiReqMsg");
		CarInfo oldCarInfo = (CarInfo)simulateApiReqMsg.getData().get("carInfo");
		oldCarInfo.setFrameNo(carInfo.getVin());
		oldCarInfo.setEngineNo(carInfo.getEngineNo());
		oldCarInfo.setBrandName(carInfo.getBrandName());
		oldCarInfo.setBrandCode(carInfo.getBrandCode());
		oldCarInfo.setIsTrans(carInfo.getIsTrans());
		oldCarInfo.setRegisterDate(carInfo.getRegisterDate());
		oldCarInfo.setTransDate(carInfo.getTransDate());
		SimulateApiReqMsg.buildMessageByCar(oldCarInfo, simulateApiReqMsg);
		TWeixinTruckInfo tWeixinTruckInfo = new TWeixinTruckInfo();
		tWeixinTruckInfo.setFrameno(carInfo.getVin());
		tWeixinTruckInfo.setEngineno(carInfo.getEngineNo());
		tWeixinTruckInfo.setBrandname(carInfo.getBrandName());
		tWeixinTruckInfo.setBrandcode(carInfo.getBrandCode());
		tWeixinTruckInfo.setIstrans(carInfo.getIsTrans());
		tWeixinTruckInfo.setRegisterdate(carInfo.getRegisterDate());
		tWeixinTruckInfo.setTransdate(carInfo.getTransDate());
		tWeixinTruckInfo.setModifydate(new Date());
		tWeixinTruckInfo.setUserid(userid);
		tWeixinTruckInfo.setVehiclefgwcode(oldCarInfo.getVehicleFgwCode());
		TWeixinTruckInfo findTruckInfo = weixinTruckInfoMapper.findTruckInfo(userid);
		if(findTruckInfo == null){
			tWeixinTruckInfo.setId(UniqId.getUid());
			tWeixinTruckInfo.setCreatedate(new Date());
			weixinTruckInfoMapper.insertSelective(tWeixinTruckInfo);
		}else{
			tWeixinTruckInfo.setId(findTruckInfo.getId());
			weixinTruckInfoMapper.updateByPrimaryKeySelective(tWeixinTruckInfo);
		}
		return getSimulateApi(session, carInsurancePrice, simulateApiReqMsg);
	}
	@SuppressWarnings("unchecked")
	@Override
	public Message update(HttpServletRequest request, JSONObject obj) throws Exception {
		HttpSession session = request.getSession();
		String userid = session.getAttribute("userid").toString();
		CarInsurancePrice carInsurancePrice= (CarInsurancePrice)session.getAttribute("carInsurancePrice");
		SimulateApiReqMsg simulateApiReqMsg = (SimulateApiReqMsg)session.getAttribute("simulateApiReqMsg");
		JSONArray coverages = obj.getJSONArray("coverageList");
		simulateApiReqMsg.getData().put("CoverageList", (List<Coverage>)obj.get("coverageList"));
		simulateApiReqMsg.getData().put("biBeginDate", obj.getString("biBeginDate"));
		simulateApiReqMsg.getData().put("ciBeginDate", obj.getString("ciBeginDate")); 
		coverageMapper.deleteAll(userid);
		List<Coverage> list = Lists.newArrayList();
		for (Object object : coverages) {
			JSONObject fromObject = JSONObject.fromObject(object);
			Coverage bean = (Coverage) JSONObject.toBean(fromObject, Coverage.class);
			bean.setId(UniqId.getUid());
			bean.setUserid(userid);
			bean.setCreatedate(new Date());
			list.add(bean);
		}
		coverageMapper.insertList(list);
		Coveragedate findCoveragedate = coveragedateMapper.findCoveragedate(userid);
		if(findCoveragedate == null){
			findCoveragedate = new Coveragedate();
			findCoveragedate.setId(UniqId.getUid());
			findCoveragedate.setBibegindate(obj.getString("biBeginDate"));
			findCoveragedate.setCibegindate(obj.getString("ciBeginDate"));
			findCoveragedate.setUserid(userid);
			coveragedateMapper.insertSelective(findCoveragedate);
		}else{
			findCoveragedate.setBibegindate(obj.getString("biBeginDate"));
			findCoveragedate.setCibegindate(obj.getString("ciBeginDate"));
			coveragedateMapper.updateByPrimaryKeySelective(findCoveragedate);
		}
		return getSimulateApi(session, carInsurancePrice, simulateApiReqMsg);
	}
	private Message getSimulateApi(HttpSession session, CarInsurancePrice carInsurancePrice,
			SimulateApiReqMsg simulateApiReqMsg) throws Exception {
		simulateApiReqMsg.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		JSONObject simulateApi = ECXBUtils.callApi(simulateApiReqMsg, PropertiesUtil.getMessage("SimulateApi"));
		if("1".equals(simulateApi.get("state"))){
			JSONObject simulateDate = simulateApi.getJSONObject("data");
			if("1".equals(simulateDate.get("state"))){
				JSONArray jsonArrays= simulateDate.getJSONArray("Data");
				List<Insurance> insurers = (List<Insurance>)carInsurancePrice.getInsurance().getData();
				for (int x=0;x<insurers.size();x++) {
					Insurance insurance = insurers.get(x);
					for (Object object : jsonArrays) {
						JSONObject fromObject = JSONObject.fromObject(object);
						if(insurance.getInsurerCode().equals(fromObject.getString("insurerCode"))){
							insurance.setQuoteResult(object);
						}
					}
					if(insurance.getQuoteResult() == null){
						insurers.remove(insurance);
						x--;
					}
				}
				carInsurancePrice.setInsurance(Message.success("Success", insurers));
			}else{
				return BaseController.error("9999");
			}
		}else{
			return Message.error(simulateApi.getString("msg"));
		}
		session.setAttribute("simulateApiReqMsg", simulateApiReqMsg);
		session.setAttribute("carInsurancePrice", carInsurancePrice);
		return BaseController.success("成功", carInsurancePrice);
	}
	@Override
	public Message send(String mobile) throws Exception {
		log.info(mobile);
		String taken = PhoneCode.sendCode(mobile, 1);
		RedisUtils.del(mobile);
		RedisUtils.setStr(mobile, taken, 60);
		return Message.success("获取成功", taken.trim());
	}
	@Override
	public Message accurate(HttpServletRequest request, Accurate accurate) throws Exception {
		if(accurate.getVerifyCode().equals(RedisUtils.getStr(accurate.getOwnerMobile()).trim())){
			HttpSession session = request.getSession();
			SimulateApiReqMsg simulateApiReqMsg = (SimulateApiReqMsg)session.getAttribute("simulateApiReqMsg");
			CarInsurancePrice carInsurancePrice= (CarInsurancePrice)session.getAttribute("carInsurancePrice");
			simulateApiReqMsg.getData().put("insurerCode", accurate.getInsuranceCode());
			PersonInfo personInfo = new PersonInfo();
			personInfo.setOwnerID(accurate.getOwnerID());
			personInfo.setInsuranceCode(accurate.getInsuranceCode());
			personInfo.setOwnerMobile(accurate.getOwnerMobile());
			personInfo.setOwnerName(accurate.getOwnerName());
			CalculateApiResultMsg calculateApiResultMsg = new CalculateApiResultMsg();
			calculateApiResultMsg.setPersonInfo(personInfo);
			personInfo.setApplicantID(accurate.getOwnerID());
			personInfo.setApplicantMobile(accurate.getOwnerMobile());
			personInfo.setApplicantName(accurate.getOwnerName());
			personInfo.setInsuredID(accurate.getOwnerID());
			personInfo.setInsuredMobile(accurate.getOwnerMobile());
			personInfo.setInsuredName(accurate.getOwnerName());
			CalculateApiReqMsg calculateApiReqMsg = CalculateApiReqMsg.buildMessage(simulateApiReqMsg, personInfo);
			JSONObject calculateApi = ECXBUtils.callApi(calculateApiReqMsg, PropertiesUtil.getMessage("CalculateApiUri"));
			List<Insurance> insurers = (List<Insurance>)carInsurancePrice.getInsurance().getData();
			Insurance in = new Insurance();
			for (Insurance insurance : insurers) {
				if(insurance.getInsurerCode().equals(accurate.getInsuranceCode())){
					in = insurance;
				}
			}
			String bizID = "";
			if("1".equals(calculateApi.getString("state"))){
				JSONArray jsonArray = calculateApi.getJSONArray("Data");
				in.setData(jsonArray);
				in.setState("1");
				JSONObject fromObject = JSONObject.fromObject(jsonArray.get(0));
				bizID = fromObject.getString("bizID");
				in.setTotalPremium((new BigDecimal(fromObject.getString("biPremium")).add(new BigDecimal(fromObject.getString("rebates")))).toString());
			}else{
				in.setState(calculateApi.getString("state"));
				in.setMsg(calculateApi.getString("msg"));
			}
			calculateApiResultMsg.setQuoteInfo(in);
			calculateApiResultMsg.setCarInfo((CarInfo)simulateApiReqMsg.getData().get("carInfo"));
			session.setAttribute("insurerCode", accurate.getInsuranceCode());
			session.setAttribute("bizID", bizID);
			return Message.success("成功", calculateApiResultMsg);
		}
		return Message.error("请输入正确的验证码");
	}
	@Override
	public Message dictList() throws Exception {
		List<Province> Provinces= tProvinceMapper.findDictList();
		Map<String, List<Province>> map = new HashMap<String, List<Province>>();
		map.put("data", Provinces);
		return Message.success("成功", map);
	}
	@Override
	public Message reinsurance(HttpServletRequest request, Reinsurance reinsurance) throws Exception {
		ReinsuranceReqMsg buildMessage = ReinsuranceReqMsg.buildMessage(reinsurance.getInsurerCode(), 
				reinsurance.getBizID(), reinsurance);
		JSONObject json = ECXBUtils.callApi(buildMessage, PropertiesUtil.getMessage("ReinsurApiUrl"));
		if(json == null){
			return Message.error("请求超时");
		}
		HttpSession session = request.getSession();
		String user_id = session.getAttribute("user_id").toString();
		TReceivers tReceivers = new TReceivers();
		tReceivers.setUser_id(Integer.valueOf(user_id));
		tReceivers.setUser_name(reinsurance.getAddresseeName());
		tReceivers.setMobile(reinsurance.getAddresseeMobile());
		tReceivers.setAddress(reinsurance.getAddresseeDetails());
		tReceivers.setIs_default(0);
		tReceivers.setProvince_id(tProvinceMapper.findByGbcode(reinsurance.getAddresseeProvince()).getProvinceId());
		tReceivers.setCity_id(tCityMapper.findByCode(reinsurance.getAddresseeCity()).getCityID());
		tReceivers.setCreate_time(new Date());
		tReceivers.setPostcode(new BigDecimal(610000));
		tReceiversMapper.myInsert(tReceivers);
		String userid = session.getAttribute("userid").toString();
		TWeixinTruckInfo tWeixinTruckInfo = new TWeixinTruckInfo();
		tWeixinTruckInfo.setUserid(userid);
		TWeixinTruckInfo findTruckInfo = weixinTruckInfoMapper.selectOne(tWeixinTruckInfo);
		TCustomerInfo tCustomerInfo = new TCustomerInfo();
		List<TCustomerInfo> findByDocCode = tCustomerInfoMapper.findByDocCode(findTruckInfo.getOwnerIdNo());
		if(findByDocCode.size() == 0 ){
			tCustomerInfo.setDoc_code(findTruckInfo.getOwnerIdNo());
			tCustomerInfo.setCustomer_name(findTruckInfo.getOwnerName());
			tCustomerInfo.setDoc_type_id(1);
			tCustomerInfo.setIsImmevalid(1);
			tCustomerInfo.setIs_enabled(0);
			tCustomerInfo.setIs_locked(0);
			tCustomerInfo.setMobile(findTruckInfo.getOwnerMobile());
			tCustomerInfo.setEmail("1615134901@qq.com");
			tCustomerInfo.setCar_insurance_id(new Integer(session.getAttribute("car_id").toString()));
			tCustomerInfo.setOwner_id(Integer.valueOf(user_id));
			tCustomerInfo.setCreate_date(new Date());
			tCustomerInfo.setReceive_rec_id(tReceivers.getId());
			String ownerIdNo = findTruckInfo.getOwnerIdNo();
			String ownerBirthday = getBirthdayByIdNo(ownerIdNo);
			String pro=ownerIdNo.substring(0, 2)+"0000";
	    	String ci=ownerIdNo.substring(0,4)+"00";
	    	String di=ownerIdNo.substring(0,6);
	    	tCustomerInfo.setProvince(pro);
	    	tCustomerInfo.setCity(ci);
			tCustomerInfo.setCounty(di);
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            tCustomerInfo.setBirthday(sdf.parse(ownerBirthday));
			String sexnumber= ownerIdNo.substring(ownerIdNo.length()-2,ownerIdNo.length()-1);
			if(Integer.parseInt(sexnumber)==0){
				tCustomerInfo.setGender(0);
			}else if(Integer.parseInt(sexnumber)%2==0){
				tCustomerInfo.setGender(0);
			}else{
				tCustomerInfo.setGender(1);
			}
			tCustomerInfoMapper.myInsert(tCustomerInfo);
		}else{
			tCustomerInfo = findByDocCode.get(0);
			tCustomerInfoMapper.updateMobile(findTruckInfo.getOwnerMobile(), tCustomerInfo.getId());
		}
		TCarprofile tCarprofile = new TCarprofile();
		tCarprofile.setLicenseNo(findTruckInfo.getLicenseno());
		TCarprofile select = tCarprofileMapper.findByLicenseNo(findTruckInfo.getLicenseno());
		if(select == null){		
			tCarprofile.setOwner_id(tCustomerInfo.getId());
			tCarprofile.setNoLicenseFlag(1);
			tCarprofile.setCityPlate(findTruckInfo.getLicenseno().substring(0, 2));
			tCarprofile.setVehicleFrameNo(findTruckInfo.getFrameno());
			tCarprofile.setEngine_code(findTruckInfo.getEngineno());
			tCarprofile.setVehicleModel_id(tCarTypesMapper.findByBrandCode(findTruckInfo.getBrandcode()).get(0).getId());
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			tCarprofile.setRegister_date(sdf.parse(findTruckInfo.getRegisterdate()));
			tCarprofile.setIsLoanCar(0);
			tCarprofile.setSpecialCarFlag(new Integer(findTruckInfo.getIstrans()));
			tCarprofile.setStatus(0);
			tCarprofile.setCity_code(new Integer(reinsurance.getAddresseeCity()));
			tCarprofile.setCreatetime(new Date()); 
			tCarprofile.setCreate_user_id(Integer.valueOf(user_id));
			tCarprofileMapper.myInsert(tCarprofile);
		}else{
			tCarprofile = select;
		}
		String randomUUID = ApplicationUtils.randomUUID();
		TCarInsuranceOrder tCarInsuranceOrder = new TCarInsuranceOrder();
		tCarInsuranceOrder.setCarId(tCarprofile.getId());
		tCarInsuranceOrder.setCustomerId(tCustomerInfo.getId());
		tCarInsuranceOrder.setUserId(Integer.valueOf(user_id));
		tCarInsuranceOrder.setIsValid(false);
		tCarInsuranceOrder.setTotalCost(reinsurance.getMoney());
		tCarInsuranceOrder.setPolicyCode(randomUUID);
		tCarInsuranceOrder.setInsUnitId(tInsuranceUnitMapper.findByUnitCode(reinsurance.getInsurerCode()));
		tCarInsuranceOrder.setOrderTime(new Date());
		Coveragedate findCoveragedate = coveragedateMapper.findCoveragedate(userid);
		tCarInsuranceOrder.setCityId(tCityMapper.findByCode(findCoveragedate.getCitycode()).getCityID());
		tCarInsuranceOrder.setCommStartDate(findCoveragedate.getBibegindate());
		tCarInsuranceOrder.setCompulsoryStartDate(findCoveragedate.getCibegindate());
		tCarInsuranceOrder.setInsSameOwnerFlag("1".equals(findTruckInfo.getIsrecognizee()));
		tCarInsuranceOrder.setHolderSameOwnerFlag("1".equals(findTruckInfo.getIsapplicant()));
		tCarInsuranceOrder.setQryServiceNo(randomUUID);
		tCarInsuranceOrder.setContent(reinsurance.getContent());
		String info = reinsurance.getInfo();
		String[] split = info.split(",");
		if("1".equals(json.getString("state"))){
			JSONObject fromObject = JSONObject.fromObject(json.get("Data"));
			tCarInsuranceOrder.setBiProposalNo(fromObject.getString("biProposalNo"));
			tCarInsuranceOrder.setCiProposalNo(fromObject.getString("ciProposalNo"));
			tCarInsuranceOrder.setReturnServiceNo(fromObject.getString("bizID"));
			if("0".equals(fromObject.getString("synchFlag"))){ 
				tCarInsuranceOrder.setStatus(1);
				tCarInsuranceOrderMapper.myInsert(tCarInsuranceOrder);
				for (String string : split) {
					String[] split2 = string.split("-");
					TInsOrderCost tInsOrderCost = new TInsOrderCost();
					tInsOrderCost.setCost(new BigDecimal(split2[2]));
					tInsOrderCost.setWarrantyCost(StringUtil.isEmpty(split2[1].trim()) ? null : new BigDecimal(split2[1]));
					TInsuranceTypes tInsuranceTypes = new TInsuranceTypes();
					tInsuranceTypes.setCode(split2[0]);
					tInsOrderCost.setInsCatId(tInsuranceTypesMapper.select(tInsuranceTypes).get(0).getId());
					tInsOrderCost.setOrderId(tCarInsuranceOrder.getId());
					tInsOrderCostMapper.insertSelective(tInsOrderCost);
				}
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("money", tCarInsuranceOrder.getTotalCost());
				map.put("id", fromObject.getString("bizID"));
				map.put("date", tCarInsuranceOrder.getOrderTime());
				return Message.success("成功", map);
			}else{
				tCarInsuranceOrder.setStatus(0);
				tCarInsuranceOrderMapper.myInsert(tCarInsuranceOrder);
				for (String string : split) {
					String[] split2 = string.split("-");
					TInsOrderCost tInsOrderCost = new TInsOrderCost();
					tInsOrderCost.setCost(new BigDecimal(split2[2]));
					tInsOrderCost.setWarrantyCost(StringUtil.isEmpty(split2[1].trim()) ? null : new BigDecimal(split2[1]));
					TInsuranceTypes tInsuranceTypes = new TInsuranceTypes();
					tInsuranceTypes.setCode(split2[0]);
					tInsOrderCost.setInsCatId(tInsuranceTypesMapper.select(tInsuranceTypes).get(0).getId());
					tInsOrderCost.setOrderId(tCarInsuranceOrder.getId());
					tInsOrderCostMapper.insertSelective(tInsOrderCost);
				}
				return Message.error("异步核保");
			}
			
		}
		tCarInsuranceOrder.setStatus(14);
		tCarInsuranceOrder.setErrorMsg(json.getString("msg"));
		tCarInsuranceOrderMapper.myInsert(tCarInsuranceOrder);
		for (String string : split) {
			String[] split2 = string.split("-");
			TInsOrderCost tInsOrderCost = new TInsOrderCost();
			tInsOrderCost.setCost(new BigDecimal(split2[2]));
			tInsOrderCost.setWarrantyCost(StringUtil.isEmpty(split2[1].trim()) ? null : new BigDecimal(split2[1]));
			TInsuranceTypes tInsuranceTypes = new TInsuranceTypes();
			tInsuranceTypes.setCode(split2[0]);
			tInsOrderCost.setInsCatId(tInsuranceTypesMapper.select(tInsuranceTypes).get(0).getId());
			tInsOrderCost.setOrderId(tCarInsuranceOrder.getId());
			tInsOrderCostMapper.insertSelective(tInsOrderCost);
		}
		return Message.error(json.getString("msg"));
	}
	
	public String getBirthdayByIdNo(String IdNo)  {
		String birthday = IdNo.substring(6, 10)+"-"+IdNo.substring(10, 12)+"-"+IdNo.substring(12, 14);
		return birthday;
	}
	@Override
	public Message saveTruckCardNew(HttpServletRequest request, String truckCard, String ownerName) throws Exception {
		TWeixinUser weixinUser = new TWeixinUser();
    	HttpSession session = request.getSession();
    	Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
		weixinUser.setOpenid(userinfo.getOpenid());
		weixinUser.setTruckcard(truckCard);
		List<TWeixinUser> tWeixinUsers = weixinUserMapper.select(weixinUser);
		if(tWeixinUsers.size() == 0){
			weixinUser.setId(UniqId.getUid());
			weixinUser.setOwnername(ownerName);
			weixinUser.setCreatedate(new Date());
			weixinUserMapper.insertSelective(weixinUser);		
		}else{
			weixinUser = tWeixinUsers.get(0);
		}
		CarInfo carInfo = new CarInfo(); 
		carInfo.setLicenseNo(truckCard);
		TWeixinTruckInfo tWeixinTruckInfo = new TWeixinTruckInfo();
		tWeixinTruckInfo.setUserid(weixinUser.getId());
		TWeixinTruckInfo findTruckInfo = weixinTruckInfoMapper.selectOne(tWeixinTruckInfo);
		if(findTruckInfo == null){
			CarInfoReqMsg carInfoReqMsg = CarInfoReqMsg.buildMessage(carInfo);
			JSONObject callApi = ECXBUtils.callApi(carInfoReqMsg, PropertiesUtil.getMessage("carInfo"));
			if(!"1".equals(callApi.get("state"))){
				return BaseController.error("0201");
			}
			JSONObject date = callApi.getJSONObject("data"); 
			if("null".equals(date.getString("vehicleList"))){
				carInfo.setFrameNo(date.getString("frameNo"));
				carInfo.setEngineNo(date.getString("engineNo"));
				carInfo.setRegisterDate(date.getString("firstRegisterDate"));
			}else{	
				JSONArray jsonArray = date.getJSONArray("vehicleList");
				JSONObject one = JSONObject.fromObject(jsonArray.get(0));
				carInfo.setFrameNo(one.getString("vin"));
				carInfo.setEngineNo(one.getString("engineNo"));
				carInfo.setBrandCode(one.getString("brandCode"));
				carInfo.setBrandName(one.getString("brandName"));
				carInfo.setIsTrans(one.getString("isTrans"));
				carInfo.setTransDate(one.getString("transDate"));
				carInfo.setRegisterDate(one.getString("registerDate"));
				carInfo.setVehicleFgwCode(one.getString("vehicleFgwCode"));
				List<Map> maps = Lists.newArrayList();
				for (Object object : jsonArray) {
					JSONObject fromObject = JSONObject.fromObject(object);
					Map<String, String> map = new HashMap<String, String>();
					StringBuffer sb = new StringBuffer();
					sb.append(fromObject.get("standardName"));
					sb.append(fromObject.get("engineDesc"));
					sb.append(fromObject.get("parentVehName"));
					map.put("vehicle", sb.toString());
					map.put("brandCode", (String) fromObject.get("brandCode"));
					maps.add(map);
					List<TCarTypes> tCarType = tCarTypesMapper.findByBrandCode(fromObject.getString("brandCode"));
					if(tCarType.size() == 0){
						TCarTypes tCarTypes =  new TCarTypes();
						tCarTypes.setType_name(fromObject.getString("brandName"));
						tCarTypes.setVehicleFgwCode(fromObject.getString("vehicleFgwCode"));
						tCarTypes.setBrandCode(fromObject.getString("brandCode"));
						tCarTypes.setBrandName(fromObject.getString("brandName"));
						tCarTypes.setEngineDesc(fromObject.getString("engineDesc"));
						tCarTypes.setFamilyName(fromObject.getString("familyName"));
						tCarTypes.setRemark(fromObject.getString("remark"));
						tCarTypes.setNewCarPrice(fromObject.getString("newCarPrice"));
						tCarTypes.setPurchasePrice(fromObject.getString("newCarPrice"));
						tCarTypes.setImportFlag(fromObject.getString("importFlag"));
						tCarTypes.setPurchasePriceTax(fromObject.getString("purchasePriceTax"));
						tCarTypes.setSeat(fromObject.getString("seat"));
						tCarTypes.setStandardName(fromObject.getString("standardName"));
						tCarTypes.setMsg("msg");
						tCarTypesMapper.myInsert(tCarTypes);
					}
				}
				carInfo.setVehicleList(maps);
			}
		}else{
			carInfo.setFrameNo(findTruckInfo.getFrameno());
			carInfo.setEngineNo(findTruckInfo.getEngineno());
			carInfo.setBrandName(findTruckInfo.getBrandname());
			carInfo.setBrandCode(findTruckInfo.getBrandcode());
			carInfo.setIsTrans(findTruckInfo.getIstrans());
			carInfo.setRegisterDate(findTruckInfo.getRegisterdate());
			carInfo.setTransDate(findTruckInfo.getTransdate());
			carInfo.setVehicleFgwCode(findTruckInfo.getVehiclefgwcode());
			carInfo.setApplicantIdCard(findTruckInfo.getApplicantIdCard());
			carInfo.setApplicantName(findTruckInfo.getApplicantName());
			carInfo.setApplicantPhone(findTruckInfo.getApplicantPhone());
			carInfo.setOwnerIdNo(findTruckInfo.getOwnerIdNo());
			carInfo.setOwnerMobile(findTruckInfo.getOwnerMobile());
			carInfo.setOwnerName(findTruckInfo.getOwnerName());
			carInfo.setRecognizeeIdCard(findTruckInfo.getRecognizeeIdCard());
			carInfo.setRecognizeeName(findTruckInfo.getRecognizeeName());
			carInfo.setRecognizeePhone(findTruckInfo.getRecognizeePhone());
			List<Map> maps = Lists.newArrayList();
			Map<String, String> map = new HashMap<String, String>();
			map.put("vehicle", findTruckInfo.getVehiclelist());
			map.put("brandCode", findTruckInfo.getBrandcode());
			maps.add(map);
			carInfo.setVehicleList(maps);
		}
		session.setAttribute("userid", weixinUser.getId());
		return Message.success("成功", carInfo);
	}
	@Override
	public Message saveTruckInfoNew(String openId, CarInfo carInfo) {
		TWeixinTruckInfo tWeixinTruckInfo = new TWeixinTruckInfo();
		tWeixinTruckInfo.setFrameno(carInfo.getVin());
		tWeixinTruckInfo.setEngineno(carInfo.getEngineNo());
		tWeixinTruckInfo.setBrandname(carInfo.getBrandName());
		tWeixinTruckInfo.setBrandcode(carInfo.getBrandCode());
		tWeixinTruckInfo.setIstrans(carInfo.getIsTrans());
		tWeixinTruckInfo.setIsapplicant(carInfo.getIsapplicant());
		tWeixinTruckInfo.setIsrecognizee(carInfo.getIsrecognizee());
		tWeixinTruckInfo.setApplicantIdCard(carInfo.getApplicantIdCard());
		tWeixinTruckInfo.setApplicantName(carInfo.getApplicantName());
		tWeixinTruckInfo.setApplicantPhone(carInfo.getApplicantPhone());
		tWeixinTruckInfo.setOwnerIdNo(carInfo.getOwnerIdNo());
		tWeixinTruckInfo.setOwnerMobile(carInfo.getOwnerMobile());
		tWeixinTruckInfo.setOwnerName(carInfo.getOwnerName());
		tWeixinTruckInfo.setRecognizeeIdCard(carInfo.getRecognizeeIdCard());
		tWeixinTruckInfo.setRecognizeeName(carInfo.getRecognizeeName());
		tWeixinTruckInfo.setRecognizeePhone(carInfo.getRecognizeePhone());
		tWeixinTruckInfo.setRegisterdate(carInfo.getRegisterDate());
		tWeixinTruckInfo.setTransdate(carInfo.getTransDate());
		tWeixinTruckInfo.setModifydate(new Date()); 
		tWeixinTruckInfo.setLicenseno(carInfo.getLicenseNo());
		TWeixinUser tWeixinUser = getWexinUser(openId, carInfo.getLicenseNo()).get(0);
		tWeixinTruckInfo.setUserid(tWeixinUser.getId());
		tWeixinTruckInfo.setVehiclefgwcode(carInfo.getVehicleFgwCode());
		tWeixinTruckInfo.setVehiclelist(carInfo.getBrandName());
		TWeixinTruckInfo truckInfo = new TWeixinTruckInfo();
		truckInfo.setUserid(tWeixinUser.getId());
		TWeixinTruckInfo findTruckInfo = weixinTruckInfoMapper.selectOne(truckInfo);
		if(findTruckInfo == null){
			tWeixinTruckInfo.setId(UniqId.getUid());
			tWeixinTruckInfo.setCreatedate(new Date());
			weixinTruckInfoMapper.insertSelective(tWeixinTruckInfo);
		}else{
			tWeixinTruckInfo.setId(findTruckInfo.getId());
			weixinTruckInfoMapper.updateByPrimaryKeySelective(tWeixinTruckInfo);
		}
		List<Coverage> selectAll = coverageMapper.selectAllByUser(tWeixinUser.getId());
		Map<String, Object> map = new HashMap<String, Object>();
		if(selectAll.size() == 0){	
			QueryInsurReqMsg queryInsurReqMsg = QueryInsurReqMsg.buildMessage(carInfo);
			JSONObject queryInsur = ECXBUtils.callApi(queryInsurReqMsg, PropertiesUtil.getMessage("queryInsur"));
			if(!"1".equals(queryInsur.get("state"))){
				return Message.error(queryInsur.getString("msg"));
			}		
			if(queryInsur.getJSONObject("data") == null){
				Date date=new  Date();//取时间 
				Calendar calendar = new GregorianCalendar(); 
				calendar.setTime(date); 
				calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动 
				date=calendar.getTime();   //这个时间就是日期往后推一天的结果 
				String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
				List<Coverage> coverageList = coverageMapper.selectTemp();
				map.put("coverageList", coverageList);
				map.put("biBeginDate", time);
				map.put("ciBeginDate", time);
			}else{
				JSONObject fromObject = JSONObject.fromObject(queryInsur.getJSONObject("data"));
				List<Coverage> coverageList = null;
				if(!"null".equals(fromObject.getString("coverageList"))){
					coverageList = fromObject.getJSONArray("coverageList");
					map.put("coverageList", coverageList);
					map.put("biBeginDate", fromObject.getString("biBeginDate"));
					map.put("ciBeginDate", fromObject.getString("ciBeginDate"));
				}else{
					Date date=new  Date();//取时间 
					Calendar calendar = new GregorianCalendar(); 
					calendar.setTime(date); 
					calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动 
					date=calendar.getTime();   //这个时间就是日期往后推一天的结果 
					String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
					coverageList = coverageMapper.selectTemp();
					map.put("coverageList", coverageList);
					map.put("biBeginDate", time);
					map.put("ciBeginDate", time);
				}
			}
		}else{
			Coveragedate findCoveragedate = coveragedateMapper.findCoveragedate(tWeixinUser.getId());
			map.put("coverageList", selectAll);
			map.put("biBeginDate", findCoveragedate.getBibegindate());
			map.put("ciBeginDate", findCoveragedate.getCibegindate());
			map.put("citycode", findCoveragedate.getCitycode());
		}
		return Message.success("成功", map);
	}
	private List<TWeixinUser> getWexinUser(String openId, String licenseNo) {
		TWeixinUser weixinUser = new TWeixinUser();
		weixinUser.setOpenid(openId);
		weixinUser.setTruckcard(licenseNo);
		List<TWeixinUser> tWeixinUsers = weixinUserMapper.select(weixinUser);
		return tWeixinUsers;
	}
	@Override
	public Message saveCoverageNew(HttpServletRequest request, JSONObject obj) throws Exception {
		JSONArray coverages = obj.getJSONArray("coverageList");
		HttpSession session = request.getSession();
		String userid = session.getAttribute("userid").toString();
		coverageMapper.deleteAll(userid);
		List<Coverage> list = Lists.newArrayList();
		for (Object object : coverages) {
			JSONObject fromObject = JSONObject.fromObject(object);
			Coverage bean = (Coverage) JSONObject.toBean(fromObject, Coverage.class);
			bean.setId(UniqId.getUid());
			bean.setUserid(userid);
			bean.setCreatedate(new Date());
			list.add(bean);
		}
		coverageMapper.insertList(list);
		Coveragedate findCoveragedate = coveragedateMapper.findCoveragedate(userid);
		if(findCoveragedate == null){
			findCoveragedate = new Coveragedate();
			findCoveragedate.setId(UniqId.getUid());
			findCoveragedate.setBibegindate(obj.getString("biBeginDate"));
			findCoveragedate.setCibegindate(obj.getString("ciBeginDate"));
			findCoveragedate.setCitycode(obj.getString("citycode"));
			findCoveragedate.setUserid(userid);
			coveragedateMapper.insertSelective(findCoveragedate);
		}else{
			findCoveragedate.setBibegindate(obj.getString("biBeginDate"));
			findCoveragedate.setCibegindate(obj.getString("ciBeginDate"));
			findCoveragedate.setCitycode("citycode");
			coveragedateMapper.updateByPrimaryKeySelective(findCoveragedate);
		}
		TCity findByCode = tCityMapper.findByCode(obj.getString("citycode"));
		List<Insurance> insurers = tProvinceMapper.findInsurance(findByCode.getProvinceID());
		return Message.success("成功", insurers);
	}
	@Override
	public Message quoteSimulate(HttpServletRequest request, String insurerCode) throws Exception {
		HttpSession session = request.getSession();
		String userid = session.getAttribute("userid").toString();
		TWeixinTruckInfo tWeixinTruckInfo = new TWeixinTruckInfo();
		tWeixinTruckInfo.setUserid(userid);
		TWeixinTruckInfo findTruckInfo = weixinTruckInfoMapper.selectOne(tWeixinTruckInfo);
		Coveragedate findCoveragedate = coveragedateMapper.findCoveragedate(userid);
		CarInfo carInfo = new CarInfo(); 
		carInfo.setLicenseNo(findTruckInfo.getLicenseno());
		carInfo.setFrameNo(findTruckInfo.getFrameno());
		carInfo.setEngineNo(findTruckInfo.getEngineno());
		carInfo.setBrandName(findTruckInfo.getBrandname());
		carInfo.setBrandCode(findTruckInfo.getBrandcode());
		carInfo.setIsTrans(findTruckInfo.getIstrans());
		carInfo.setRegisterDate(findTruckInfo.getRegisterdate());
		carInfo.setTransDate(findTruckInfo.getTransdate());
		carInfo.setVehicleFgwCode(findTruckInfo.getVehiclefgwcode());
		List<Coverage> selectAll = coverageMapper.selectAllByUser(userid);
		SimulateApiReqMsg simulateApiReqMsg =  SimulateApiReqMsg.buildMessage(carInfo, insurerCode, 
				findCoveragedate.getBibegindate(), findCoveragedate.getCibegindate(), findCoveragedate.getCitycode(), selectAll);
		PersonInfo personInfo = new PersonInfo();
		personInfo.setOwnerID(findTruckInfo.getOwnerIdNo());
		personInfo.setInsuranceCode(insurerCode);
		personInfo.setOwnerMobile(findTruckInfo.getOwnerMobile());
		personInfo.setOwnerName(findTruckInfo.getOwnerName());
		personInfo.setApplicantID(findTruckInfo.getApplicantIdCard());
		personInfo.setApplicantMobile(findTruckInfo.getApplicantPhone());
		personInfo.setApplicantName(findTruckInfo.getApplicantName());
		personInfo.setInsuredID(findTruckInfo.getRecognizeeIdCard());
		personInfo.setInsuredMobile(findTruckInfo.getRecognizeePhone());
		personInfo.setInsuredName(findTruckInfo.getRecognizeeName());
		CalculateApiReqMsg calculateApiReqMsg = CalculateApiReqMsg.buildMessage(simulateApiReqMsg, personInfo);
		JSONObject calculateApi = ECXBUtils.callApi(calculateApiReqMsg, PropertiesUtil.getMessage("CalculateApiUri"));
		Insurance in = new Insurance();
		if(calculateApi == null){
			return Message.error("请求超时");
		}
		if("1".equals(calculateApi.getString("state"))){
			JSONArray jsonArray = calculateApi.getJSONArray("Data");
			in.setData(jsonArray);
			in.setState("1");
			for (Object object : jsonArray) {
				JSONObject fromObject = JSONObject.fromObject(object);
				String string = fromObject.getString("CoverageList");
				if(!"null".equals(string)){
					in.setTotalPremium((new BigDecimal(fromObject.getString("biPremium")).subtract(StringUtil.isEmpty(fromObject.getString("rebates"))?BigDecimal.ZERO:new BigDecimal(fromObject.getString("rebates")))
							.add(StringUtil.isEmpty(fromObject.getString("ciPremium"))?BigDecimal.ZERO:new BigDecimal(fromObject.getString("ciPremium"))).add(StringUtil.isEmpty(fromObject.getString("carshipTax"))?BigDecimal.ZERO:new BigDecimal(fromObject.getString("carshipTax")))).toString());
					TCarInsurance tCarInsurance = new TCarInsurance();
					tCarInsurance.setLicenseNo(findTruckInfo.getLicenseno());
					tCarInsurance.setFrameNo(findTruckInfo.getFrameno());
					tCarInsurance.setEngineNo(findTruckInfo.getEngineno());
					tCarInsurance.setBiDate(findCoveragedate.getBibegindate());
					tCarInsurance.setCiDate(findCoveragedate.getCibegindate());
					tCarInsurance.setInsuranceUnit(insurerCode);
					tCarInsurance.setInsuranceContent(calculateApi.getString("Data"));
					tCarInsurance.setBiOrderNumber("");
					tCarInsurance.setCiOrderNumber("");
					TCarInsurance findByLicenseNo = tCarInsuranceMapper.findByLicenseNo(findTruckInfo.getLicenseno());
					if(findByLicenseNo == null){	
						tCarInsuranceMapper.insert(tCarInsurance);
						session.setAttribute("car_id", tCarInsurance.getId());
					}else{
						tCarInsurance.setId(findByLicenseNo.getId());
						tCarInsuranceMapper.update(tCarInsurance);
						session.setAttribute("car_id", tCarInsurance.getId());
					}
					break;
				}
			}		
		}else{
			in.setState(calculateApi.getString("state"));
			in.setMsg(calculateApi.getString("msg"));
		}
		in.settWeixinTruckInfo(findTruckInfo);
		return Message.success("成功", in);
	}
	@Override
	public Message getVagueCity(String cityName) throws Exception {
		List<TCity> vagueCity = tCityMapper.getVagueCity(cityName);
		return Message.success("成功", vagueCity);
	}
	@Override
	public Message addAddress(TWeixinAddress tWeixinAddress) throws Exception {
		if("1".equals(tWeixinAddress.getIsdefault())){
			tWeixinAddressMapper.removeDefault(tWeixinAddress.getOpenid());
		}
		if(StringUtil.isEmpty(tWeixinAddress.getId())){
			tWeixinAddress.setId(UniqId.getUid());
			tWeixinAddressMapper.insertSelective(tWeixinAddress);
		}else{
			tWeixinAddressMapper.updateByPrimaryKeySelective(tWeixinAddress);
		}
		return Message.success("成功");
	}
	@Override
	public Message delAddress(String id) throws Exception {
		tWeixinAddressMapper.deleteByPrimaryKey(id);
		return Message.success("成功");
	}
	
	@Override
	public Message getAddress(String openId) throws Exception {
		List<TWeixinAddress> selectAll = tWeixinAddressMapper.getAddressAll(openId);
		return Message.success("成功", selectAll);
	}
	@Override
	public Message setDefault(String openId, String id) throws Exception {
		tWeixinAddressMapper.removeDefault(openId);
		TWeixinAddress selectByPrimaryKey = tWeixinAddressMapper.selectByPrimaryKey(id);
		selectByPrimaryKey.setIsdefault("1");
		tWeixinAddressMapper.updateByPrimaryKeySelective(selectByPrimaryKey);
		return Message.success("成功");
	}
	@Override
	public Message getCityAll() throws Exception {
		List<TCity> selectAll = tCityMapper.getCityAll();
		return Message.success("成功", selectAll);
	}
	@Override
	public Message getInsuranceAll(String cityCode) {
		List<Insurance> insurers = tProvinceMapper.findInsurance(cityCode);
		return Message.success("成功", insurers);
	}
	@Override
	public Message getJsonData() throws Exception {
		return Message.success("成功", tProvinceMapper.getJsonData());
	}
	@Override
	public Message findAddress(String id) throws Exception {
		return Message.success("成功", tWeixinAddressMapper.selectByPrimaryKey(id));
	}
	@Override
	public Message login(HttpServletRequest request, String phone, String token) throws Exception {
		String str = RedisUtils.getStr(phone);
		if(!str.trim().equals(token)){
			return Message.error("验证码错误");
		}
		HttpSession session = request.getSession();
		Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
		String openid = userinfo.getOpenid();
		TUserprofile tUserprofile = new TUserprofile();
		tUserprofile.setMobile(phone);
		List<TUserprofile> tUserprofiles = tUserprofileMapper.select(tUserprofile);
		if(tUserprofiles.size() != 0){
			TUserprofilePn2m tUserprofilePn2m = new TUserprofilePn2m();
			tUserprofilePn2m.setUser_id(tUserprofiles.get(0).getId());
			tUserprofilePn2m.setValtype("varchar");
			tUserprofilePn2m.setKeyname("openid");
			List<TUserprofilePn2m> select = tUserprofilePn2mMapper.select(tUserprofilePn2m);
			if(select.size() != 0 ){
				return Message.error("该手机号已经绑定了其他微信");
			}
			tUserprofilePn2m.setUser_id(tUserprofiles.get(0).getId());
			tUserprofilePn2m.setValtype("varchar");
			tUserprofilePn2m.setKeyname("openid");
			tUserprofilePn2m.setValdata(openid);
			tUserprofilePn2mMapper.insertSelective(tUserprofilePn2m);
			session.setAttribute("user_id", tUserprofiles.get(0).getId());
			return Message.success();
		}
		tUserprofile.setAlias_name(userinfo.getNickname());
		tUserprofile.setPwd("123456");
		tUserprofile.setType_id(1);
		tUserprofile.setRegister_time(new Date());
		tUserprofile.setIs_admin(1);
		tUserprofile.setIs_enabled(0);
		tUserprofile.setIs_locked(0);
		tUserprofile.setIsrealname(0);
		tUserprofileMapper.myInsert(tUserprofile);
		String pwd = MD5.UMencode(tUserprofile.getMobile(), String.valueOf(tUserprofile.getId()));
		tUserprofile.setPwd(pwd);
		tUserprofileMapper.updateByPrimaryKeySelective(tUserprofile);
		TUserprofilePn2m tUserprofilePn2m = new TUserprofilePn2m();
		tUserprofilePn2m.setUser_id(tUserprofile.getId());
		tUserprofilePn2m.setValtype("varchar");
		tUserprofilePn2m.setKeyname("openid");
		tUserprofilePn2m.setValdata(openid);
		tUserprofilePn2mMapper.insertSelective(tUserprofilePn2m);
		TAccount tAccount = new TAccount();
		tAccount.setUserId(tUserprofile.getId());
		tAccount.setBalance(BigDecimal.ZERO);
		tAccount.setCash(BigDecimal.ZERO);
		tAccount.setPayPassword("");
		tAccount.setIslocked(0);
		tAccountMapper.insert(tAccount);
		session.setAttribute("user_id", tUserprofile.getId());
		return Message.success();
	}
	@Override
	public Message getOrder(String user_id, String type, Integer rows) {
		List<OrderResultMsg> list = Lists.newArrayList();
		rows = rows == null ? 0 : rows;
		PageHelper.startPage(rows, 10);
		if("0".equals(type)){
			list = tCarInsuranceOrderMapper.getAllOrder(user_id);
		}else if("1".equals(type)){
			list = tCarInsuranceOrderMapper.getOrder("(1,16)",user_id);
		}else if("2".equals(type)){
			list = tCarInsuranceOrderMapper.getOrder("(2,3,4)",user_id);
		}
		return Message.success(list);
	}
	@Override
	public Message getOrderInfo(String id) {
		TCarInsuranceOrderExtend orderInfo = tCarInsuranceOrderMapper.getOrderInfo(id);
		TInsOrderCost tInsOrderCost = new TInsOrderCost();
		tInsOrderCost.setOrderId(Integer.valueOf(id));
		List<TInsOrderCostExtends> tInsOrderCostExtends = Lists.newArrayList();
		List<TInsOrderCost> tInsOrderCosts = tInsOrderCostMapper.select(tInsOrderCost);
		for (TInsOrderCost tInsOrderCost2 : tInsOrderCosts) {
			TInsOrderCostExtends tInsOrderCostExtend = new TInsOrderCostExtends();
			tInsOrderCostExtend.setCost(tInsOrderCost2.getCost());
			tInsOrderCostExtend.setWarrantyCost(tInsOrderCost2.getWarrantyCost());
			tInsOrderCostExtend.setName(tInsuranceTypesMapper.selectByPrimaryKey(tInsOrderCost2.getInsCatId()).getTypeName());
			tInsOrderCostExtends.add(tInsOrderCostExtend);
		}
		orderInfo.settInsOrderCosts(tInsOrderCostExtends);
		return Message.success(orderInfo);
	}
	@Override
	public Message delOrder(Integer id) {
		tCarInsuranceOrderMapper.delOrder(id);
		return Message.success("删除成功");
	}
	@Override
	public Message getCustomer(HttpServletRequest request, String order, Integer isValid) {
		HttpSession session = request.getSession();
		String user_id = session.getAttribute("user_id").toString();
		Integer userId = Integer.valueOf(user_id);
		List<CustomerResult> tCustomerInfos = Lists.newArrayList();
		if(isValid == 2){
			if("0".equals(order)){
				tCustomerInfos = tCustomerInfoMapper.findTCustomerInfoOrderByOrderStartTimeAll(userId);
			}else{
				tCustomerInfos = tCustomerInfoMapper.findTCustomerInfoOrderByOrderTimeAll(userId);
			}
		}else{
			if("0".equals(order)){
				tCustomerInfos = tCustomerInfoMapper.findTCustomerInfoOrderByOrderStartTime(userId,isValid);
			}else{
				tCustomerInfos = tCustomerInfoMapper.findTCustomerInfoOrderByOrderTime(userId,isValid);
			}
		}
		for (CustomerResult customerResult : tCustomerInfos) {
			customerResult.settCarprofiles(tCarprofileMapper.findByCustomerId(customerResult.getId()));
		}
		return Message.success(tCustomerInfos);
	}

}
